package com.ywz.common;

import java.time.LocalDate;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 类描述 -> ID生成器
 *
 * @Author: ywz
 * @Date: 2025/02/20
 */
public class IDGenerator {
    /**
     * 方法描述 -> 生成ID
     *
     * @param prefix 前缀
     * @Author: ywz
     * @Date: 2025/02/20
     */
    public static String generateId(String prefix) {
        try {
            TimeUnit.MILLISECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        String year = String.valueOf(LocalDate.now().getYear());
        String month = String.valueOf(LocalDate.now().getMonthValue());
        String day = String.valueOf(LocalDate.now().getDayOfMonth());
        if (month.length() == 1)
            month = "0" + month;
        if (day.length() == 1)
            day = "0" + day;
        if (StringUtils.isEmpty(prefix))
            return year + month + day + "_" + System.currentTimeMillis();
        return prefix + year + month + day + "_" + System.currentTimeMillis();
    }

    /**
     * 方法描述 -> 生成并发ID
     *
     * @param prefix 前缀
     * @Author: ywz
     * @Date: 2025/04/02
     */
    public static String generateConcurrentId(String prefix) {
        Random random = new Random();
        String year = String.valueOf(LocalDate.now().getYear());
        String month = String.valueOf(LocalDate.now().getMonthValue());
        String day = String.valueOf(LocalDate.now().getDayOfMonth());
        if (month.length() == 1)
            month = "0" + month;
        if (day.length() == 1)
            day = "0" + day;
        if (StringUtils.isEmpty(prefix))
            return year + month + day + "_" + System.nanoTime() + random.nextInt(1000);
        return prefix + year + month + day + "_" + System.nanoTime() + random.nextInt(1000);
    }
}
